"                                                                                                          "
" ██    ██ ██ ███    ███     ██ ███████      █████  ██     ██ ███████ ███████  ██████  ███    ███ ███████  "
" ██    ██ ██ ████  ████     ██ ██          ██   ██ ██     ██ ██      ██      ██    ██ ████  ████ ██       "
" ██    ██ ██ ██ ████ ██     ██ ███████     ███████ ██  █  ██ █████   ███████ ██    ██ ██ ████ ██ █████    "
"  ██  ██  ██ ██  ██  ██     ██      ██     ██   ██ ██ ███ ██ ██           ██ ██    ██ ██  ██  ██ ██       "
"   ████   ██ ██      ██     ██ ███████     ██   ██  ███ ███  ███████ ███████  ██████  ██      ██ ███████  "
"                                                                                                          "
" Install Plug
if empty(glob('~/.config/nvim/autoload/plug.vim'))
  silent !curl -fLo ~/.config/nvim/autoload/plug.vim --create-dirs
    \ https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
  autocmd VimEnter * PlugInstall --sync | source $MYVIMRC
endif

" Plug Manager
call plug#begin('~/.config/nvim/plug')

" let g:plug_url_format = 'https://gitee.com/%s.git'
let g:plug_url_format = 'git@gitee.com:%s.git'

" themes
Plug 'vim-plug-mirror/NeoSolarized'
Plug 'vim-plug-mirror/rainbow'
Plug 'vim-plug-mirror/vim-nerdtree-syntax-highlight'

" git
Plug 'vim-plug-mirror/vim-fugitive'
Plug 'vim-plug-mirror/vim-gitgutter'
" Plug 'vim-plug-mirror/ConflictMotions'

" auto complete
" Plug 'Valloric/YouCompleteMe'
Plug 'vim-plug-mirror/coc.nvim', {'branch': 'release'}
Plug 'vim-plug-mirror/auto-pairs'
Plug 'vim-plug-mirror/nvim-lspconfig'

" python dev
" Plug 'davidhalter/jedi-vim'
" show indent line
Plug 'vim-plug-mirror/indentLine'
Plug 'vim-plug-mirror/python-mode', { 'for': 'python', 'branch': 'main' }

" grammar check/highlight
Plug 'vim-plug-mirror/ale'
Plug 'vim-plug-mirror/vim-easy-align'
Plug 'vim-plug-mirror/vim-virtualenv'
Plug 'vim-plug-mirror/nerdcommenter'

" golang dev
Plug 'mirrors/vim-go'

" rust
Plug 'vim-plug-mirror/rust.vim'
" run :CocInstall coc-rust-analyzer after installation

" sh
Plug 'vim-plug-mirror/vim-shfmt', { 'for': 'sh'  }

" hive sql
Plug 'vim-plug-mirror/hive.vim'
" Plug 'vim-plug-mirror/Vim'

" toml
Plug 'vim-plug-mirror/vim-toml'

" thrift
Plug 'vim-plug-mirror/thrift.vim'

" NERDTree
Plug 'vim-plug-mirror/nerdtree'
Plug 'vim-plug-mirror/nerdtree-git-plugin'

Plug 'vim-plug-mirror/vim-airline'
Plug 'vim-plug-mirror/vim-airline-themes'
" Plug 'vim-plug-mirror/vim-devicons'

" tools
Plug 'vim-plug-mirror/vim-startify'
Plug 'vim-plug-mirror/LeaderF'
Plug 'vim-plug-mirror/tagbar'
Plug 'vim-plug-mirror/ag.vim'
Plug 'vim-plug-mirror/vim-ripgrep'
" Plug 'epmatsw/ag.vim'
" Plug 'mileszs/ack.vim'

Plug 'vim-plug-mirror/FlyGrep.vim'
Plug 'vim-plug-mirror/incsearch.vim'
Plug 'vim-plug-mirror/vim-easymotion'
Plug 'vim-plug-mirror/undotree'
Plug 'vim-plug-mirror/vim-surround'
Plug 'vim-plug-mirror/vim-multiple-cursors'
Plug 'vim-plug-mirror/vim-better-whitespace'

Plug 'vim-plug-mirror/vim-cursorword'
Plug 'vim-plug-mirror/vim-interestingwords'
Plug 'vim-plug-mirror/vim-table-mode'

" snippets
Plug 'vim-plug-mirror/ultisnips'
Plug 'vim-plug-mirror/vim-snippets'

call plug#end()

" ----------------------------------------------------------------------------------------------------------------------
" basic config
set termguicolors
colorscheme NeoSolarized
set background=dark

set shortmess=atI
set backspace=indent,eol,start
set number                     " AKA nu
set relativenumber             " AKA rnu
set ruler
set showcmd
set showmatch
set cursorline
syntax on
set incsearch                  " find as you type search
set hlsearch                   " highlight search terms
set winminheight=0             " windows can be 0 line high
set ignorecase                 " case insensitive search
set smartcase                  " case sensitive when uc present
set wildmenu                   " show list instead of just completing
set wildmode=list:longest,full " command <Tab> completion, list matches, then longest common part, then all.
set whichwrap=b,s,h,l,<,>,[,]  " backspace and cursor keys wrap to
set scrolljump=5               " lines to scroll when cursor leaves screen
set scrolloff=3                " minimum lines to keep above and below cursor
set foldenable                 " auto fold code
set gdefault                   " the /g flag on :s substitutions by default
set clipboard+=unnamedplus
let g:solarized_termcolors=256

set encoding=utf-8
set fenc=utf-8
set fencs=utf-8,usc-bom,euc-jp,gb18030,gbk,gb2312,cp936

" set indent for most codes
set expandtab
set autoindent
set fileformat=unix

set tabstop=4
set softtabstop=4
set shiftwidth=4

set foldmethod=indent
set textwidth=120

" .py files
autocmd BufNewFile,BufRead *.py
\ set tabstop=4 |
\ set softtabstop=4 |
\ set shiftwidth=4

autocmd BufNewFile,BufRead *.yaml,*.yml,*.json,*.ps1,*.lua
\ set tabstop=2 |
\ set softtabstop=2 |
\ set shiftwidth=2

autocmd FileType gitconfig
\ set tabstop=4 |
\ set softtabstop=4 |
\ set shiftwidth=4

autocmd FileType vim
\ set tabstop=2 |
\ set softtabstop=2 |
\ set shiftwidth=2

" map <leader> to `,`, default '\'
let g:mapleader = ","
nnoremap ; :
nmap <leader>e :e $MYVIMRC<CR>
nmap <leader>r :so $MYVIMRC<CR>

" Remember to execute /usr/local/bin/python3 -m pip install neovim
if filereadable('/usr/local/bin/python3')
  let g:python3_host_prog = '/usr/local/bin/python3'
else
  let g:python3_host_prog = '/usr/bin/python3'
endif
let python_highlight_all = 1

" indentLine
let g:indentLine_char_list = ['|', '¦', '┆', '┊']
let g:indentLine_fileTypeExclude = ['defx', 'denite', 'dashboard', 'tagbar', 'vista_kind', 'vista', 'startify', 'nerdtree', 'txt', 'log']
let g:indentLine_concealcursor = 'niv'

":verbose set conceallevel 查看哪个插件设置的值
autocmd FileType json,markdown let g:indentLine_conceallevel = 0


" ale config
let g:ale_sign_error = '✗'
let g:ale_sign_warning = '--'

" for .hql files
autocmd BufNewFile,BufRead *.hql set filetype=hive expandtab
" for .q files
autocmd BufNewFile,BufRead *.q set filetype=hive expandtab

" ==# 大小写敏感的等于判断
" ==? 大小写不敏感的等于判断
" type :h exp4 to see more comparement
autocmd BufWinEnter quickfix nnoremap <silent> <buffer>
  \   q :cclose<cr>:lclose<cr>
autocmd BufEnter * if (winnr('$') == 1 && &buftype ==# 'quickfix' ) |
  \   bd|
  \   q | endif

" ----------------------------------------------------------------------------------------------------------------------
" startify
let s:header = [
      \ '',
      \ '',
      \ '',
      \' ██╗░░██╗░█████╗░██╗██╗░░░░░  ███╗░░░███╗███████╗░██████╗░░█████╗░████████╗██████╗░░█████╗░███╗░░██╗',
      \' ██║░░██║██╔══██╗██║██║░░░░░  ████╗░████║██╔════╝██╔════╝░██╔══██╗╚══██╔══╝██╔══██╗██╔══██╗████╗░██║',
      \' ███████║███████║██║██║░░░░░  ██╔████╔██║█████╗░░██║░░██╗░███████║░░░██║░░░██████╔╝██║░░██║██╔██╗██║',
      \' ██╔══██║██╔══██║██║██║░░░░░  ██║╚██╔╝██║██╔══╝░░██║░░╚██╗██╔══██║░░░██║░░░██╔══██╗██║░░██║██║╚████║',
      \' ██║░░██║██║░░██║██║███████╗  ██║░╚═╝░██║███████╗╚██████╔╝██║░░██║░░░██║░░░██║░░██║╚█████╔╝██║░╚███║',
      \' ╚═╝░░╚═╝╚═╝░░╚═╝╚═╝╚══════╝  ╚═╝░░░░░╚═╝╚══════╝░╚═════╝░╚═╝░░╚═╝░░░╚═╝░░░╚═╝░░╚═╝░╚════╝░╚═╝░░╚══╝',
      \ '',
      \ '',
      \ '',
      \ ]

let s:footer = [
      \ '',
      \' ███████╗░█████╗░██████╗░  ░█████╗░██╗░░░██╗██████╗░███████╗██████╗░████████╗██████╗░░█████╗░███╗░░██╗',
      \' ██╔════╝██╔══██╗██╔══██╗  ██╔══██╗╚██╗░██╔╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔══██╗██╔══██╗████╗░██║',
      \' █████╗░░██║░░██║██████╔╝  ██║░░╚═╝░╚████╔╝░██████╦╝█████╗░░██████╔╝░░░██║░░░██████╔╝██║░░██║██╔██╗██║',
      \' ██╔══╝░░██║░░██║██╔══██╗  ██║░░██╗░░╚██╔╝░░██╔══██╗██╔══╝░░██╔══██╗░░░██║░░░██╔══██╗██║░░██║██║╚████║',
      \' ██║░░░░░╚█████╔╝██║░░██║  ╚█████╔╝░░░██║░░░██████╦╝███████╗██║░░██║░░░██║░░░██║░░██║╚█████╔╝██║░╚███║',
      \' ╚═╝░░░░░░╚════╝░╚═╝░░╚═╝  ░╚════╝░░░░╚═╝░░░╚═════╝░╚══════╝╚═╝░░╚═╝░░░╚═╝░░░╚═╝░░╚═╝░╚════╝░╚═╝░░╚══╝',
      \ '',
      \ ]

let g:startify_custom_header = startify#center(s:header)
let g:startify_custom_footer = startify#center(s:footer)

function! s:set_startify_left_padding() abort
  let g:startify_padding_left = winwidth(0)/2 - 20
endfunction

autocmd! FileType startify
autocmd  FileType startify set laststatus=0 showtabline=0
  \| autocmd BufLeave <buffer> set laststatus=2 showtabline=2
autocmd User Startified setlocal buflisted
" autocmd VimEnter * call s:set_startify_left_padding()

" plugins config
" NERDTree
" open a NERDTree automatically when vim starts up
" autocmd VimEnter * NERDTree
" place the cursor in the editor
autocmd VimEnter * wincmd w
" open a NERDTree automatically when vim starts up if no files were specified
" autocmd StdinReadPre * let s:std_in=1
" autocmd VimEnter * if argc() == 0 && !exists("s:std_in") | NERDTree | endif

" open NERDTree automatically when vim starts up on opening a directory
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * if argc() == 1 && isdirectory(argv()[0]) && !exists("s:std_in") | exe 'NERDTree' argv()[0] | wincmd p | ene | endif

" close vim when the only left open is a NERDTree
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif

" If another buffer tries to replace NERDTree, put it in the other window, and bring back NERDTree.
autocmd BufEnter * if bufname('#') =~ 'NERD_tree_\d\+' && bufname('%') !~ 'NERD_tree_\d\+' && winnr('$') > 1 |
    \ let buf=bufnr() | buffer# | execute "normal! \<C-W>w" | execute 'buffer'.buf | endif

map <leader>t :NERDTreeToggle<CR>
" locate current file
map <leader>l :NERDTreeFind<cr>

" Change default arrows
" let g:NERDTreeDirArrowExpandable = '📁'
" let g:NERDTreeDirArrowCollapsible = '📂'
let g:NERDTreeDirArrowExpandable = '|+|'
let g:NERDTreeDirArrowCollapsible = '|-|'

let g:NERDTreeGitStatusIndicatorMapCustom = {
  \ "Modified"  : "✹",
  \ "Staged"    : "✚",
  \ "Untracked" : "✭",
  \ "Renamed"   : "➜",
  \ "Unmerged"  : "═",
  \ "Deleted"   : "✖",
  \ "Dirty"     : "✗",
  \ "Clean"     : "✔︎",
  \ 'Ignored'   : '☒',
  \ "Unknown"   : "?"
  \ }


" display row number in NERDTree
" let NERDTreeShowLineNumbers = 1
" set width
" let NERDTreeWinSize=20
let NERDTreeIgnore = ['\.pyc$', '\.pyo$', '\~$', '__pycache__$[[dir]]', '\.swp$', 'node_modules']

" close rainbow in nerdtree
let g:rainbow_conf = {
\    'separately': {
\       'nerdtree': 0
\    }
\}

" airline settings.
let g:airline_theme = 'solarized'
let g:airline_solarized_bg='dark'
let g:airline_powerline_fonts = 1

if !exists('g:airline_symbols')
  let g:airline_symbols = {}
endif

let g:airline_left_sep = ''
let g:airline_left_alt_sep = ''
let g:airline_right_sep = ''
let g:airline_right_alt_sep = ''
let g:airline_symbols.branch = ''
let g:airline_symbols.readonly = ''
let g:airline_symbols.linenr = '␊'
let g:airline_symbols.maxlinenr = '㏑'

" show absolute file path in status line
let g:airline_section_c = '%<%F%m %#__accent_red#%{airline#util#wrap(airline#parts#readonly(),0)}%#__restore__#'
" show tab number in tab line
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tabline#tab_nr_type = 1
let g:airline#extensions#tabline#formatter = 'default'
let g:airline#extensions#tabline#left_sep = ''
let g:airline#extensions#tabline#left_alt_sep = ''
let g:airline#extensions#tabline#right_sep = ''
let g:airline#extensions#tabline#right_alt_sep = ''

let g:airline#extensions#bufferline#enabled = 1

" leaderF config
let g:Lf_ShortcutF = "<leader>ff"
noremap <leader>fb :<C-U><C-R>=printf("Leaderf buffer %s", "")<CR><CR>
noremap <leader>fm :<C-U><C-R>=printf("Leaderf mru %s", "")<CR><CR>
noremap <leader>ft :<C-U><C-R>=printf("Leaderf bufTag %s", "")<CR><CR>
noremap <leader>fl :<C-U><C-R>=printf("Leaderf line %s", "")<CR><CR>
" let g:Lf_WindowPosition = 'popup'
" 禁用缓存
let g:Lf_UseCache = 0
let g:Lf_UseVersionControlTool = 0
let g:Lf_UseMemoryCache = 0
let g:Lf_PreviewInPopup = 1
let g:Lf_StlSeparator = { 'left': "\ue0b0", 'right': "\ue0b2", 'font': "DejaVu Sans Mono for Powerline" }
let g:Lf_PreviewResult = {'Function': 1, 'BufTag': 0, 'File': 1 }
" 设置项目根目录模式
let g:Lf_WorkingDirectoryMode = 'AF'
let g:Lf_RootMarkers = ['.git', '.svn', '.hg', '.project', '.root']
" autocmd BufNewFile,BufRead X:/yourdir* let g:Lf_WildIgnore={'file':['*.vcproj', '*.vcxproj'],'dir':[]}
let g:Lf_WildIgnore={
      \ 'file':['*.vcproj', '*.vcxproj', '*.exe', '*.so', '*.sw?', '*.o', '*.py[co]'],
      \ 'dir':['.git', '.node_modules', '.hg',]
      \ }
let g:Lf_StlColorscheme = 'powerline'

if has('nvim')
    let s:cachedir = expand(stdpath('cache'))
    let s:configdir = expand(stdpath('config'))
else
    "vim will share same folder with nvim
    if has('win32')
        let s:cachedir = expand('~/AppData/Local/Temp/cache/nvim')
        let s:configdir = expand('~/AppData/Local/nvim')
    else
        let s:cachedir = expand('~/.cache/nvim')
        let s:configdir = expand('~/.config/nvim')
    endif
endif
let g:Lf_CacheDirectory = s:cachedir

" YCM configs
" let g:ycm_autoclose_preview_window_after_completion = 1
" let g:ycm_key_invoke_completion = '<C-z>'
" let g:ycm_min_num_identifier_candidate_chars = 2
" 屏蔽 YCM 的诊断信息
" let g:ycm_show_diagnostics_ui = 0
" let g:ycm_collect_identifiers_from_comments_and_strings = 0

let g:rainbow_active = 1

" devicons config
if exists("g:loaded_webdevicons")
  call webdevicons#refresh()
endif
let g:airline_powerline_fonts = 1
let g:webdevicons_enable_vimfiler = 0
let g:WebDevIconsNerdTreeAfterGlyphPadding = ' '
let g:WebDevIconsNerdTreeGitPluginForceVAlign = 0

" Tagbar
" map <C-m> :TagbarToggle<CR>

" nerdtree highlighting
let g:NERDTreeFileExtensionHighlightFullName = 1
let g:NERDTreeExactMatchHighlightFullName = 1
let g:NERDTreePatternMatchHighlightFullName = 1

" fugitive
" this makes Gdiff uses vertical spilter
set diffopt+=vertical

" gitgutter
let g:gitgutter_sign_modified = '>'
let g:gitgutter_sign_modified_removed = '>_'

" better whitespace config: do not show whitespace when open the following file types
let g:better_whitespace_filetypes_blacklist=['<etc>', 'startify', 'diff', 'git',
      \ 'gitcommit', 'unite', 'qf', 'help', 'markdown', 'fugitive']

" NERDCommenter
" Add spaces after comment delimiters by default
let g:NERDSpaceDelims = 1
" Align line-wise comment delimiters flush left instead of following code indentation
let g:NERDDefaultAlign = 'left'
" Enable trimming of trailing whitespace when uncommenting
let g:NERDTrimTrailingWhitespace = 1
" Enable NERDCommenterToggle to check all selected lines is commented or not
let g:NERDToggleCheckAllLines = 1

" easy align
" Start interactive EasyAlign in visual mode (e.g. vipga)
xmap ga <Plug>(EasyAlign)
" Start interactive EasyAlign for a motion/text object (e.g. gaip)
nmap ga <Plug>(EasyAlign)

" for ack
" if executable('ag')
  " let g:ackprg = 'ag --vimgrep'
" endif

" shfmt
let g:shfmt_fmt_on_save = 1
let g:shfmt_extra_args = '-i 4'

" vim-multiple-cursors
let g:multi_cursor_use_default_mapping = 0
" Default mapping
let g:multi_cursor_start_word_key      = '<C-n>'
let g:multi_cursor_select_all_word_key = '<A-n>'
let g:multi_cursor_start_key           = 'g<C-n>'
let g:multi_cursor_select_all_key      = 'g<A-n>'
let g:multi_cursor_next_key            = '<C-n>'
let g:multi_cursor_prev_key            = '<C-p>'
let g:multi_cursor_skip_key            = '<C-x>'
let g:multi_cursor_quit_key            = '<Esc>'
" let g:multi_cursor_start_word_key = '<C-n>'

" vim-table-mode configs
let g:table_mode_corner='|'
function! s:isAtStartOfLine(mapping)
  let text_before_cursor = getline('.')[0 : col('.')-1]
  let mapping_pattern = '\V' . escape(a:mapping, '\')
  let comment_pattern = '\V' . escape(substitute(&l:commentstring, '%s.*$', '', ''), '\')
  return (text_before_cursor =~? '^' . ('\v(' . comment_pattern . '\v)?') . '\s*\v' . mapping_pattern . '\v$')
endfunction

inoreabbrev <expr> <bar><bar>
          \ <SID>isAtStartOfLine('\|\|') ?
          \ '<c-o>:TableModeEnable<cr><bar><space><bar><left><left>' : '<bar><bar>'
inoreabbrev <expr> __
          \ <SID>isAtStartOfLine('__') ?
          \ '<c-o>:silent! TableModeDisable<cr>' : '__'

" nvim coc configs
" TextEdit might fail if hidden is not set.
set hidden

" Some servers have issues with backup files, see #649.
set nobackup
set nowritebackup

" Give more space for displaying messages.
set cmdheight=2

" Having longer updatetime (default is 4000 ms = 4 s) leads to noticeable
" delays and poor user experience.
set updatetime=300

" Don't pass messages to |ins-completion-menu|.
set shortmess+=c

" Always show the signcolumn, otherwise it would shift the text each time
" diagnostics appear/become resolved.
set signcolumn=yes

" Use tab for trigger completion with characters ahead and navigate.
" NOTE: There's always complete item selected by default, you may want to enable
" no select by `"suggest.noselect": true` in your configuration file.
" NOTE: Use command ':verbose imap <tab>' to make sure tab is not mapped by
" other plugin before putting this into your config.
inoremap <silent><expr> <TAB>
      \ coc#pum#visible() ? coc#pum#next(1) :
      \ CheckBackspace() ? "\<Tab>" :
      \ coc#refresh()
inoremap <expr><S-TAB> coc#pum#visible() ? coc#pum#prev(1) : "\<C-h>"

" Make <CR> to accept selected completion item or notify coc.nvim to format
" <C-g>u breaks current undo, please make your own choice.
" inoremap <silent><expr> <CR> coc#pum#visible() ? coc#pum#confirm() : "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"
inoremap <silent><expr> <TAB> coc#pum#visible() ? coc#pum#confirm() : "\<C-g>u\<TAB>"

function! CheckBackspace() abort
  let col = col('.') - 1
  return !col || getline('.')[col - 1]  =~# '\s'
endfunction

" Use <c-space> to trigger completion.
if has('nvim')
  inoremap <silent><expr> <c-space> coc#refresh()
else
  inoremap <silent><expr> <c-@> coc#refresh()
endif

" Use <cr> to confirm completion, `<C-g>u` means break undo chain at current
" position. Coc only does snippet and additional edit on confirm.
" <cr> could be remapped by other vim plugin, try `:verbose imap <CR>`.
if exists('*complete_info')
  inoremap <expr> <cr> complete_info()["selected"] != "-1" ? "\<C-y>" : "\<C-g>u\<CR>"
else
  inoremap <expr> <cr> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
endif

" Use `[g` and `]g` to navigate diagnostics
nmap <silent> [g <Plug>(coc-diagnostic-prev)
nmap <silent> ]g <Plug>(coc-diagnostic-next)

" GoTo code navigation.
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gi <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)

" Use K to show documentation in preview window.
nnoremap <silent> K :call ShowDocumentation()<CR>

function! ShowDocumentation()
  if CocAction('hasProvider', 'hover')
    call CocActionAsync('doHover')
  else
    call feedkeys('K', 'in')
  endif
endfunction


" Highlight the symbol and its references when holding the cursor.
autocmd CursorHold * silent call CocActionAsync('highlight')

" Symbol renaming.
nmap <leader>rn <Plug>(coc-rename)

" Formatting selected code.
xmap <leader>F  <Plug>(coc-format-selected)
nmap <leader>F  <Plug>(coc-format-selected)

augroup mygroup
  autocmd!
  " Setup formatexpr specified filetype(s).
  autocmd FileType typescript,json setl formatexpr=CocAction('formatSelected')
  " Update signature help on jump placeholder.
  autocmd User CocJumpPlaceholder call CocActionAsync('showSignatureHelp')
augroup end

" Applying codeAction to the selected region.
" Example: `<leader>aap` for current paragraph
xmap <leader>a  <Plug>(coc-codeaction-selected)
nmap <leader>a  <Plug>(coc-codeaction-selected)

" Remap keys for applying codeAction to the current buffer.
nmap <leader>ac  <Plug>(coc-codeaction)
" Apply AutoFix to problem on the current line.
nmap <leader>qf  <Plug>(coc-fix-current)

" Run the Code Lens action on the current line.
nmap <leader>cl  <Plug>(coc-codelens-action)

" Map function and class text objects
" NOTE: Requires 'textDocument.documentSymbol' support from the language server.
xmap if <Plug>(coc-funcobj-i)
omap if <Plug>(coc-funcobj-i)
xmap af <Plug>(coc-funcobj-a)
omap af <Plug>(coc-funcobj-a)
xmap ic <Plug>(coc-classobj-i)
omap ic <Plug>(coc-classobj-i)
xmap ac <Plug>(coc-classobj-a)
omap ac <Plug>(coc-classobj-a)

" Remap <C-f> and <C-b> for scroll float windows/popups.
if has('nvim-0.4.0') || has('patch-8.2.0750')
  nnoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>"
  nnoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>"
  inoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(1)\<cr>" : "\<Right>"
  inoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(0)\<cr>" : "\<Left>"
  vnoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>"
  vnoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>"
endif

" Use CTRL-S for selections ranges.
" Requires 'textDocument/selectionRange' support of language server.
nmap <silent> <C-s> <Plug>(coc-range-select)
xmap <silent> <C-s> <Plug>(coc-range-select)

" Add `:Format` command to format current buffer.
command! -nargs=0 Format :call CocActionAsync('format')

" Add `:Fold` command to fold current buffer.
command! -nargs=? Fold :call     CocAction('fold', <f-args>)

" Add `:OR` command for organize imports of the current buffer.
command! -nargs=0 OR   :call     CocActionAsync('runCommand', 'editor.action.organizeImport')

" Add (Neo)Vim's native statusline support.
" NOTE: Please see `:h coc-status` for integrations with external plugins that
" provide custom statusline: lightline.vim, vim-airline.
set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')}

" Mappings for CoCList
" Show all diagnostics.
nnoremap <silent><nowait> <space>a  :<C-u>CocList diagnostics<cr>
" Manage extensions.
nnoremap <silent><nowait> <space>e  :<C-u>CocList extensions<cr>
" Show commands.
nnoremap <silent><nowait> <space>c  :<C-u>CocList commands<cr>
" Find symbol of current document.
nnoremap <silent><nowait> <space>o  :<C-u>CocList outline<cr>
" Search workspace symbols.
nnoremap <silent><nowait> <space>s  :<C-u>CocList -I symbols<cr>
" Do default action for next item.
nnoremap <silent><nowait> <space>j  :<C-u>CocNext<CR>
" Do default action for previous item.
nnoremap <silent><nowait> <space>k  :<C-u>CocPrev<CR>
" Resume latest coc list.
nnoremap <silent><nowait> <space>p  :<C-u>CocListResume<CR>

" Trail blank characters of EOL
map <leader><space> :FixWhitespace<CR>

" coc rust-analyzer config
let g:LanguageClient_serverCommands = {
\ 'rust': ['rust-analyzer'],
\ }

let g:ale_linters = {'rust': ['analyzer']}

" pymode settings
let g:pymode = 1
let g:pymode_trim_whitespaces = 1
let g:pymode_options_max_line_length = 120
let g:pymode_lint_options_pep8 =
  \ {'max_line_length': g:pymode_options_max_line_length}

let g:pymode_rope = 1
let g:pymode_rope_refix = '<C-c>'
let g:pymode_lint_cwindow = 0
set completeopt=menuone,noinsert
let g:pymode_rope_completion = 1
let g:pymode_rope_complete_on_dot = 1
let g:pymode_rope_autoimport_modules = ['os', 'shutil', 'datetime']

" Find definition
let g:pymode_rope_goto_definition_bind = '<C-c>g'
let g:pymode_rope_goto_definition_cmd = 'new'

" vim snippets
" Trigger configuration. You need to change this to something other than <tab> if you use one of the following:
" - https://github.com/Valloric/YouCompleteMe
" - https://github.com/nvim-lua/completion-nvim
let g:UltiSnipsExpandTrigger="<cr>"
let g:UltiSnipsJumpForwardTrigger="<c-b>"
let g:UltiSnipsJumpBackwardTrigger="<c-z>"

" If you want :UltiSnipsEdit to split your window.
let g:UltiSnipsEditSplit="vertical"
